/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import entities.Cart;
import entities.Client;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;


@ManagedBean(name="loginHelper")
@RequestScoped
public class LoginHelper {
    private String login;
    private String password;
    private String errorMessage;
    private static String ERRORMESSAGE = "Niepoprawny login lub hasło";

    public LoginHelper() {
    }

    public LoginHelper(String login, String password) {
        this.login = login;
        this.password = password;
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String authenticate()
    {
        ClientDAO clientDao = new ClientDAO();
        Client client = clientDao.findClientByLogin(login, password);

        if (client!=null) {
            Cart cart = new Cart();
            CartDAO cartDao = new CartDAO();
            cartDao.create(cart);
            client.setCart(cart);

            //SessionManager sm = new SessionManager();
            SessionManager.getInstance().setSessionItem("client", client);
            SessionManager.getInstance().setSessionItem("cart", client.getCart());        // sprawdzic czy zadziala
            if(client.getLogin().equals("admin"))
                return "admin";
            else
                return "index";
        }
        else {
            errorMessage = ERRORMESSAGE;
            return null;
        }
        
    }

    public String getErrorMessage() {
        if (errorMessage==null) {
            return "";
        } else {
            return errorMessage;
        }
    }

}
